package com.pp.service.impl;

import com.pp.common.vo.ImageVO;
import com.pp.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 该类实现图片上传
 * @author
 */
@Service
public class FileServiceImpl implements FileService {

    /**本地的磁盘路径*/
    private String localDirPath = "D:/images";

    /**网页的url*/
    private String perURLPath = "http://image.cq.com";

    @Override
    public ImageVO uploader(MultipartFile file) {
        //获取上传文件的名字
        String filename = file.getOriginalFilename();
        //将图片名字全部转为小写
        filename = filename.toLowerCase();
        //如果图片不是这些格式返回null
        if (!filename.matches("^.+\\.(jpg|png)$")){
            return null;
        }
        try {
            //读取图片
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            //获取图片的宽和高
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            //如果图片的宽和高都为0,说明不是图片,返回null
            if (height==0 || width==0){
                return null;
            }
            //生成年月日格式路径 /2021/08/15
            String dateDirPath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //拼接全路径// D:/images/2021/08/15
            String localDir = localDirPath + dateDirPath;
            File dirFile = new File(localDir);
            //如果文件目录不存在
            if (!dirFile.exists()){
                //则创建目录
                dirFile.mkdirs();
            }
            //生成不重复的uuid字符串
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //截取"."后年的尾缀
            int index = filename.lastIndexOf(".");
            String fileType = filename.substring(index);
            //拼接图片名 uuid+图片的尾缀
            String realFileName = uuid+fileType;
            //拼接文件名,保证每个文件名都一样不重复
            String fullURL = localDir + realFileName;
            //图片上传
            file.transferTo(new File(fullURL));
            //D:/images/2021/08/15/***.jpg
            String virtualPath = dateDirPath + realFileName;
            //返回网络虚拟地址
            String urlPath = perURLPath + virtualPath;
            //virtualPath: 本地图片的真是路径
            //urlPath: 网络虚拟地址
            //realFileName: 生成uuid的图片名
            ImageVO imageVO = new ImageVO(virtualPath, urlPath, realFileName);
            return imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
